; (function ($) {
  const ScrollSpy = function (ele, opt) {
    this.$element = $(ele)
    this.options = $.extend({}, ScrollSpy.DEFAULTS, opt)
    this.$navBar = $('.scrollspy-nav')
    this.offsets = []
    this.targets = []
    this.target = $(this.options.target)
  }

  ScrollSpy.DEFAULTS = {
    offset: 10,
    target: window
  }

  ScrollSpy.prototype.getparams = function () {
    let self = this
    this.$navBar.find('a')
      .map(function () {
        let $el = $(this)
        let href = $(this).data('target') || $(this).attr('href')
        let $href = $(href)
        return ($href && $href.length && [[$href.offset().top, href]])
      })
      .sort(function (a, b) { return a[0] - b[0] })
      .each(function () {
        self.offsets.push(this[0])
        self.targets.push(this[1])
      })
  }

  ScrollSpy.prototype.process = function () {
    let scrollTop = $(window).scrollTop() + this.options.offset
    let i, j, length = this.targets.length;
    for (j = 0; j < length; j++) {
      if (scrollTop >= this.offsets[j]){
        i = j
      }
    }
    this.$navBar.find('a').eq(i).addClass('active').siblings().removeClass('active')
  }
  
  ScrollSpy.prototype.init = function(){
    this.target.on('scroll', $.proxy(this.process, this))
    this.getparams()
    this.process()
  }

  $.fn.scrollspy = function (options) {
    let scrollspy = new ScrollSpy(this, options)
    return this.each(function(){
      scrollspy.init()
    })
  }

  $(window).on('load', function () {
    $('[data-plugin="scrollspy"]').each(function () {
      $(this).scrollspy({
        offset: 50
      })
    })
  })
})(jQuery)